package com.blue.firecat.interceptor;

import com.blue.firecat.contants.Contants;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @描述 登录拦截器
 * @时间 2017-6-22 15:30
 * @作者 肖亦鸣
 */
public class UserInterceptor implements HandlerInterceptor {
    private static Logger logger = LogManager.getLogger(UserInterceptor.class.getName());

    //返回值表示是否要将当前的请求拦截下来
    //如果返回false,则请求终止,如果返回true,则继续放行
    //请求之前调用
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        //如果是跳转到登陆界面,则不拦截
        for (int i = 0; i < Contants.notInterceptorUrl.length; i++) {
            if (request.getRequestURL().toString().contains(Contants.notInterceptorUrl[i])) {
                return true;
            }
        }
        Object object = request.getSession().getAttribute(Contants.USER_SESSION);
        if (null == object) {
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
            logger.info("no login :{},requestUrl:{},basePath:{}", getIpAdd(request), request.getRequestURL().toString(), basePath);
            //    request.getRequestDispatcher("/index.jsp").forward(request, response);
            response.sendRedirect(basePath + "user/index.html");
            return false;
        }
        return true;
    }

    //请求时调用
    //通过modelAndView可以改变方式
    //可以改变视图转发路径
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    //请求之后
    //资源销毁
    //流的关闭等等
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

    /**
     * 获取客户的ip地址
     *
     * @param request
     * @return
     */
    private String getIpAdd(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}